package com.cyy.demo.common;

import com.cyy.demo.utils.RedisUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
 *
 * @author admin
 */
public class AccessFilter implements Filter {

    private static final Logger LOGGER = LoggerFactory.getLogger("AccessFilter");

    @Autowired
    private RedisUtils redisUtils;

    private int count ;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        count = Integer.parseInt(redisUtils.get("count"));
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        String header = request.getHeader("user-agent");
        String requestURI = request.getRequestURI();
        String remoteAddr = request.getRemoteAddr();
        count++;
        LOGGER.info("header:{},uri:{},ip:{},第{}次登陆",header,requestURI,remoteAddr,count);
        redisUtils.set("count",count);

    }

    @Override
    public void destroy() {
        redisUtils.set("count",count);
    }
}
